package com.decheng.servlet;

import com.decheng.pojo.Cart;
import com.decheng.pojo.User;
import com.decheng.service.OrderService;
import com.decheng.service.impl.OrderServiceImpl;
import com.decheng.servlet.base.BaseServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 */
public class OrderServlet extends BaseServlet {

    private OrderService orderService = new OrderServiceImpl();

    /**
     * For Test
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void toOrderPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        engine.processTemplate("order/order", request, response);
    }

    /**
     * 结账
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void checkOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1. 获取 session
        HttpSession session = request.getSession();
        // 2. 从 session 中获取用户和购物车
        Cart cart = (Cart) session.getAttribute("cart");
        User user = (User) session.getAttribute("loginUser");
        // 3. 创建订单，返回订单号
        String orderSequence = orderService.checkOut(user, cart);
        // 4. 创建订单项
        orderService.createOrderItems(cart, orderSequence);

        // 3. 获取订单对象在数据库中自增主键的值
        // 4. 根据购物车中的CartItem集合逐个创建OrderItem对象
        // 5. 把OrderItem对象的集合保存到数据库
        // 6. 每一个item对应的图书增加销量、减少库存
        // 7. 清空购物车

        // 5. 跳转到订单详情页面
        request.setAttribute("orderSequence", orderSequence);
        engine.processTemplate("cart/checkout", request, response);
    }
}
